using System.Web;
using Shinkansen.Crunchers;
using Shinkansen.Model;
using Shinkansen.Support;

namespace Shinkansen.Runtime
{
    public class StaticResourceHandler : IHttpHandler
    {
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest (HttpContext context)
        {
            ResourceInformation     ri = new ResourceInformation (context.Request.Url.Query);
            OutputProcessor         outputProcessor = new OutputProcessor (context, ri);

            CruncherBuilder         builder = CruncherBuilder.Current;
            ICssCruncher            cssCruncher = builder.GetCssCruncher ();
            IJsCruncher             jsCruncher = builder.GetJsCruncher ();

            IStaticResource resource = 
                new CachedStaticResource (
                    new CompressedStaticResource (
                        new CrunchedStaticResource (
                            new StaticResource (ri), jsCruncher, cssCruncher, ri), ri), ri);

            byte[] finalOutput = resource.GetContent ();

            outputProcessor.SetHeaders ();
            outputProcessor.SendContent (finalOutput);
        }

        /// <summary>
        /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
        /// </summary>
        /// <value></value>
        /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
        /// </returns>
        public bool IsReusable
        {
            get { return true; }
        }
    }
}